package com.walkline.util;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import net.rim.device.api.system.EncodedImage;
import net.rim.device.api.system.JPEGEncodedImage;

import com.walkline.weibo.WeiboException;

/**
 * 临时存储上传图片的内容，格式，文件信息等
 */
public class ImageItem
{
	private byte[] _content;
	private String _filename;
	private String _fullname;
	private String _contentType;
	
	private int _imageWidth;
	private int _imageHeight;
	
	public ImageItem(String filename) throws WeiboException
	{
		byte[] content;
		String imgtype = null;
		
		try {
			content = readFileImage(filename);
			imgtype = getContentType(content);
		} catch (IOException e) {throw new WeiboException(e.toString());}
		
	    if(imgtype!=null && (imgtype.equalsIgnoreCase("image/gif") || imgtype.equalsIgnoreCase("image/png") || imgtype.equalsIgnoreCase("image/jpeg")))
	    {
	    	_content=scaleImage(content);
	    	_contentType=imgtype;
	    	_fullname=filename;
	    	_filename=getFileName();
	    }else{throw new WeiboException("Unsupported image type, Only Suport JPG ,GIF,PNG!");}
	}
	
	private byte[] scaleImage(byte[] data)
	{
		EncodedImage image=EncodedImage.createEncodedImage(data, 0, data.length);
		image=Function.bestFitEncodedImage(image, 1600, 1600);
		
		JPEGEncodedImage encoder=JPEGEncodedImage.encode(image.getBitmap(),85);
		
		_imageWidth=encoder.getBitmap().getWidth();
		_imageHeight=encoder.getBitmap().getHeight();
		
		return encoder.getData();
	}
	
	public byte[] getContent() {return _content;}
	public String getFullname() {return _fullname;}
	public String getFilename() {return _filename;}
	public String getContentType() {return _contentType;}
	public int getImageWidth() {return _imageWidth;}
	public int getImageHeight() {return _imageHeight;}
	
	private byte[] readFileImage(String filename) throws IOException
	{
		FileConnection file=(FileConnection) Connector.open(filename, Connector.READ);
		int len = (int) file.fileSize();
		byte[] bytes = new byte[len];

		InputStream input=file.openInputStream();
		int r=input.read(bytes);
	
		if(len!= r)
		{
			bytes = null;
			throw new IOException("读取文件不正确");
		}
		
		if(input!=null) {try{input.close();} catch (Exception e) {}}
		if(file!=null) {try{file.close();} catch (Exception e) {}}
	
		return scaleImage(bytes);
	}	
	
	private String getFileName()
	{
		if(_fullname==null || _fullname.equals("")) {return null;}
		
		String[] filePart=StringUtility.split(_fullname, "/");
		
		return filePart[filePart.length-1];
	}
	
	private static String getContentType(byte[] mapObj) throws IOException
	{
		String type = "";
		ByteArrayInputStream bais = null;

		bais = new ByteArrayInputStream(mapObj);
		
		byte[] b=new byte[4];
		bais.read(b, 0, b.length);
		String value=bytesToHexString(b);
		
		if(value.startsWith("FFD8FF")) {type ="image/jpeg";}
		if(value.startsWith("89504E47")) {type = "image/png";}
		if(value.startsWith("47494638")) {type = "image/gif";}

		if(bais!=null) {try{bais.close();} catch(Exception e) {}}
		
		return type;
	}
	
	private static String bytesToHexString(byte[] src)
	{
		StringBuffer builder = new StringBuffer();
		
		if(src==null || src.length <= 0){return null;}
		
		String hv;
		
		for (int i=0; i<src.length; i++)
		{
			hv = Integer.toHexString(src[i] & 0xFF).toUpperCase();
			
			if (hv.length() < 2) {builder.append(0);}
			builder.append(hv);
		}

		return builder.toString();
	}	
}